package com.redis.filter.redission;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class BloomFilterService {
    /**
     * 错误概率
     */
    private final static double fpp = 0.001;
    /**
     * 数组长度
     */
    private final static Long expectedInsertions = 10000000L;

    private ConcurrentHashMap<String, RBloomFilter> bloomFilterMap = new ConcurrentHashMap<>();

    @Autowired
    private RedissonClient redissonClient;

    public RBloomFilter getBloomFilter(String key){
        RBloomFilter rBloomFilter = bloomFilterMap.get(key);
        if (null == rBloomFilter){
            synchronized (BloomFilterService.class){
                if (null == rBloomFilter){
                    rBloomFilter = redissonClient.getBloomFilter(key);
                    boolean isSuccess = rBloomFilter.tryInit(expectedInsertions, fpp);
                    if (!isSuccess){
                        log.info("生成布隆过滤器失败");
                        throw new RuntimeException("生成布隆过滤器失败");
                    }
                    // 添加
                    bloomFilterMap.put(key, rBloomFilter);
                }
            }
        }
        return rBloomFilter;
    }

    public void add(String key, String str){
        RBloomFilter bloomFilter = getBloomFilter(key);
        bloomFilter.add(str);
    }

    public boolean contains(String key, String str){
        RBloomFilter bloomFilter = getBloomFilter(key);
        return bloomFilter.contains(str);
    }
}
